<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <i class="el-icon-info" />
          <span>共16条记录</span>
        </template>
        <template #right>
          <el-button
            type="danger"
            size="small"
            @click="exportExcel"
          >普通excel导出</el-button>
          <el-button type="info" size="small">复杂标头ecxel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <!-- 新增员工按钮 -->
          <el-button
            type="primary"
            size="small"
            @click="showDialog"
          >新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img :src="row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ hireMap[row.formOfEmployment] }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <template #default="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="toDetail(row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignRole(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="params.page"
            :page-size="params.size"
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <add-employee
        :visible="dialogVisible"
        @dialog-close="dialogClose"
        @fetch-employee-list="fetchEmployeeList"
      />
      <el-dialog
        title="分配角色"
        :visible="assignRoleVisible"
        @close="assignRoleClose"
        @open="assignRoleOpen"
      >
        <!-- 角色多选框 -->
        <!-- roleIds：选中的多选框中的 label 组成的数组 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <!-- 按钮区域 -->
        <template #footer>
          <el-button size="small" @click="assignRoleClose">取消</el-button>
          <el-button type="primary" size="small" @click="submitAssginRoles">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserDetailById } from '@/api/user'
import { delEmployee, assignRoles } from '@/api/employee'
import AddEmployee from '@/components/add-employee.vue'
import dayjs from 'dayjs'
import { getEmployeeList, getRoleList } from '@/api/setting.js'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      params: {
        page: 1,
        size: 10
      },
      dialogVisible: false,
      list: [],
      total: 0,
      hireMap: {
        1: '正式',
        2: '非正式'
      },
      // 控制分配角色弹窗的显示与隐藏
      assignRoleVisible: false,
      roleList: [],
      roleIds: [],
      employeeId: ''
    }
  },
  created() {
    this.fetchEmployeeList()
  },
  methods: {
    // 分配角色弹窗打开，执行的回调
    async assignRoleOpen() {
      // 获取角色列表数据
      // 因为该接口做了分页，我们为了获取全部角色，将 page 设置为 1，pagesize 设置为 100
      const res = await getRoleList({
        page: 1,
        pagesize: 100
      })
      this.roleList = res.data.rows
      const userDetail = await getUserDetailById(this.employeeId)
      this.roleIds = userDetail.data.roleIds
    },
    // 显示分配角色弹窗
    showAssignRole(id) {
      this.assignRoleVisible = true
      this.employeeId = id
    },
    // 分配权限
    async submitAssginRoles() {
      // 调用接口
      await assignRoles({
        id: this.employeeId,
        roleIds: this.roleIds
      })
      // 提示用户
      this.$message.success('分配角色成功')
      // 关闭弹窗
      this.assignRoleClose()
    },
    // 分配角色弹窗关闭，执行的回调
    assignRoleClose() {
      this.assignRoleVisible = false
    },
    toDetail(id) {
      // 跳转到员工详情页，并传递参数
      this.$router.push({
        path: '/employeeDetail',
        query: {
          id
        }
      })
    },
    formatDate(value) {
      return dayjs(value).format('YYYY-MM-DD')
    },
    async fetchEmployeeList() {
      // 使用结构赋值的时候需要确认好结构的字段和对象中的字段是否一致
      // 使用了多层结构 （实际开发中不推荐）
      const {
        data: { rows, total }
      } = await getEmployeeList(this.params)
      this.list = rows
      this.total = total
    },
    // 展示第几页，发生变化的回调
    handleCurrentChange(newPage) {
      this.params.page = newPage
      this.fetchEmployeeList()
    },
    // 打开弹窗
    showDialog() {
      this.dialogVisible = true
    },
    // 弹窗关闭后，执行的回调
    dialogClose() {
      this.dialogVisible = false
    },
    // 删除员工
    delEmployee(id) {
      // 1. 询问用户
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 2. 调用接口
          await delEmployee(id)
          // 3. 提示用户
          this.$message.success('删除员工成功')
          // 删除最后一页最后一条数据时，页数减 1
          if (this.list.length === 1 && this.params.page > 1) {
            this.params.page--
          }
          // 4. 刷新列表
          this.fetchEmployeeList()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 导出功能
    async exportExcel() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 调用员工列表接口，获取要导出的员工列表
        const res = await getEmployeeList(this.params)
        // 数据转换
        // 表头
        const headerArr = [
          '姓名',
          '手机号',
          '入职日期',
          '工号',
          '聘用形式',
          '部门'
        ]
        // 中英对照关系
        const headerRelation = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          工号: 'workNumber',
          聘用形式: 'formOfEmployment',
          部门: 'departmentName'
        }
        // 根据员工列表数据、表头、中英文对应关系，将数据转换成二维数组
        const twoArr = this.getExportData(
          res.data.rows,
          headerArr,
          headerRelation
        )
        // 导出
        excel.export_json_to_excel({
          // 表头 header 必填，是一个数组
          header: headerArr,
          // 表格 body 具体数据，是一个二维数组
          data: twoArr,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    transEmployment(value) {
      const TYPES = {
        1: '正式',
        2: '非正式'
      }
      return TYPES[value]
    },
    getExportData(ros, headerArr, headerRelation) {
      const twoArr = []
      console.log(ros)
      ros.forEach((item) => {
        const arr = []
        headerArr.forEach((key) => {
          const enkey = headerRelation[key]
          if (enkey === 'formOfEmployment') {
            const formatValue = this.transEmployment(item[enkey])
            arr.push(formatValue)
          } else {
            arr.push(item[enkey])
          }
        })
        twoArr.push(arr)
      })
      console.log(twoArr)
      return twoArr
    }
  }
}
</script>
<style lang='less' scoped>
</style>
